package com.zzedu.framework.transaction.impl;

import com.zzedu.framework.transaction.ITransactionHandlerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.function.Supplier;

/**
 * 解决同service中非事务方法调用事务方法事务不生效
 *
 * @author Administrator
 */
@Component
public class TransactionHandlerService implements ITransactionHandlerService {

    @Autowired
    TransactionTemplate transactionTemplate;

    @Override
    public <T> T runInTransaction(Supplier<T> supplier) {
        return transactionTemplate.execute(status -> {
            try {
                return supplier.get();
            } catch (Exception e) {
                status.setRollbackOnly(); // 明确指定回滚
                throw e;
            }
        });
    }
}
